#!/bin/env python

"""
Mercurial hooks to clean-up the code in the repository.

This file is part of open-hea.

open-hea is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.

open-hea is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with open-hea.  If not, see <http://www.gnu.org/licenses/>.
"""


__author__  = 'Sarah Mount <s.mount@wlv.ac.uk>'
__date__    = '2010'
__credits__ = ''

import os
import os.path


def rmoldpyc():
    """ Searches subdirectories of the current directory looking for
        .pyc files which do not have matching .py files, and deletes
        them.

        This is useful as a hook for version control when Python files
        are moved.  It is dangerous for projects that deliberately
        include Python binaries without source.

        This code was written by Oddthinking and made public on
        StackOverflow:

        http://stackoverflow.com/questions/2528283/automatically-deleting-pyc-files-when-corresponding-py-is-moved-mercurial
    """
    print 'Running rmoldpyc hook.'
    for root, dirs, files in os.walk("."):
        pyc_files = filter(lambda filename: filename.endswith(".pyc"), files)
        py_files = set(filter(lambda filename: filename.endswith(".py"), files))
        excess_pyc_files = filter(lambda pyc_filename: pyc_filename[:-1] not in py_files, pyc_files)
        for excess_pyc_file in excess_pyc_files:
            full_path = os.path.join(root, excess_pyc_file)
            print "Removing old .pyc file:", full_path
            os.remove(full_path)
    return False # Tell Mercurial to carry on, if this is a controlling hook.

if __name__ == '__main__':
    rmoldpyc()
